package com.feifan;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.feifan.annotation.PackageScann;
import com.feifan.utils.IOCUtils;

@PackageScann
public class MyDispather extends HttpServlet {

    private static final long serialVersionUID = -7154047248664853493L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doget" + req.getRequestURI() + ":==:" + req.getRequestURL());
        resp.sendRedirect("/pages/index.html");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.err.println("dispather service()" + Thread.currentThread().getName());
        String requestURI = req.getRequestURI();
        if (requestURI.endsWith("/")) {
            requestURI = requestURI.substring(0, requestURI.length() - 1);
        }
        if (IOCUtils.getUrlMaps().containsKey(requestURI)) {
            Method method = IOCUtils.getUrlMaps().get(requestURI);
            try {
                method.invoke(IOCUtils.newInstance(method), req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            resp.getWriter().write("The URL NOT Found");
        }
    }

    @Override
    public void destroy() {
        System.err.println("dispather destory()");
    }

    /**
     * 获取所有的自定义注解类，并且实例化，并且收入BeanMap 中
     */
    @Override
    public void init() throws ServletException {
        System.out.println("dispather init()");
        // 获取扫描路径下所有的class文件,实例化注解的bean.
        IOCUtils.getBasePackage(this.getClass());
        IOCUtils.createBeanMaps();

    }

}
